<?php

/**
 * @Author: kendy
 * @Date:   2020-02-20 11:15:30
 * @Last Modified by:   jiayanting
 * @Last Modified time: 2020-02-20 11:18:11
 */
namespace app\api\model; 
use think\Model;
use think\Db; 
use app\common\model\GuideModel as g;
use app\api\model\GroupTour as gt; 
class Active extends Model
{

//根据主键id查询活动产品相关属性设置
    public static function getActivityProductsSeting( $id = 0) {
        $data = [];
        if (!is_positive_integer($id)) {
            return $data;
        }
        $sql = "SELECT a.`id`,a.`product_id`,a.`activity_money`,a.`bargain_section`,a.`join_count`,a.`product_desc`,a.`product_name`,
                a.`attr1_id`,a.`attr2_id`,
                b.`give_score`,b.`category_img`,b.`add_money`,b.`category_sum`
                FROM `hp_activity_bargain` AS a
                LEFT JOIN `hp_category_attr` AS b
                ON a.`attr1_id` = b.`attr1_son_id` AND a.`attr2_id` = b.`attr2_son_id` AND a.`product_id` = b.`category_id`
                WHERE a.`id` = $id
                LIMIT 1";
        $res = Db::query($sql);
        if (is_not_empty_array($res)) {
            $data = $res[0];
        }
        return $data;
    }
    //通过主键id拿砍价活动表的相关信息
    public static function getBargainirgProgress($id = 0) {
        $data = [];
        $sql = "SELECT `id`,`activity_bargain_id`,`product_id`,`attr1_id`,`attr2_id`,`user_id`,`bargain_count`,`deal_money`,`is_addorder` 
                FROM `hp_activity_bargainirg` 
                WHERE `id` = $id LIMIT 1";
        $res = self::query($sql);
        if (is_not_empty_array($res)) {
            $data = $res[0];
        }
        return $data;
    }
    //返回要砍
    public static function returnProgressData($a_b_id = 0, $product_id = 0, $user_id = 0, $attr1_son_id = 0, $attr2_son_id = 0, $deal_money= 0){
        $data = [];
        $sql = "SELECT `id`,`activity_bargain_id`,`product_id`,`attr1_id`,`attr2_id`,`user_id`,`bargain_count`,`deal_money`,`is_addorder`
                FROM `hp_activity_bargainirg` 
                WHERE `activity_bargain_id` = $a_b_id AND `attr1_id` = $attr1_son_id AND `attr2_id` = $attr2_son_id AND `product_id` = $product_id AND `user_id` = $user_id 
                LIMIT 1";
 
        $res = self::query($sql);
        if (is_not_empty_array($res)) {
            $data = $res[0];
        } else {
            $data['activity_bargain_id'] = $a_b_id;
            $data['product_id']          = $product_id;
            $data['user_id']             = $user_id;
            $data['deal_money']          = $deal_money; 
            $data['attr1_id']            = $attr1_son_id; 
            $data['attr2_id']            = $attr2_son_id;   
            $data['create_time']         = time(); 
            $data['bargain_count']       = 0; 
            Db::name('activity_bargainirg')->insert($data);
            $insertId =  Db::name('activity_bargainirg')->getLastInsID();
            $data['id']                  = $insertId;
            // $data = self::getBargainirgProgress($insert_id);
        }
        return $data;
    }
    //通过 表[activity_products] 主键id 和 user_id 拿到用户购买前要付款的额度和购买商品
    public static function getBargainResult2Pay($a_b_id = 0, $user_id = 0) {
        $data  = [];
        if ( !is_positive_integer($a_b_id) || !is_positive_integer($user_id)) {
            return $data;
        }
        $sql = "SELECT `id`,`deal_money`,`product_id`,`attr1_id`,`attr2_id` FROM `hp_activity_bargainirg`
                WHERE `activity_bargain_id` = $a_b_id AND `user_id` = $user_id
                LIMIT 1";
        $res = Db::query($sql);
        if (is_not_empty_array($res)) {
            $data = $res[0];
        }
        return $data;
    }
 
    //检测是否帮助伙伴砍价
    //$bargain_id       [activity_bargainirg]表主键id
    //$assistor_id      帮助砍价者用户id
    public static function checkPartBargain ($bargain_id = 0, $assistor_id = 0) {
        $state = false;
        if (!is_positive_integer($bargain_id) || !is_positive_integer($assistor_id)) {
            return $state;
        }
        $sql = "SELECT `bargain_money` FROM `hp_activity_bargain_list`
                WHERE  `bargain_id` = $bargain_id AND  `assistor_id` = $assistor_id 
                LIMIT 1";
 
        $res = self::query($sql);
 
        if (is_not_empty_array($res)) {
 
            return $res[0]['bargain_money'];
        }
        return $state;
 
    }
 
    //查询帮忙砍价的伙伴列表
    public static function getAssistorList ( $bargain_id = 0){
        $data = [];
        if (is_positive_integer($bargain_id) && is_positive_integer($assistor_id)) 
            return $data;
        $sql = "SELECT a.`create_time`, a.`bargain_money`, b.`nickname`, b.`headimgurl` 
                FROM `hp_activity_bargain_list` AS a
                LEFT JOIN `hp_user_auths` AS b
                ON a.`assistor_id` = b.`user_id`
                WHERE a.`bargain_id` = $bargain_id
                ORDER BY a.`id` DESC";
 
        $data = self::query($sql);
        return $data;
    }
 
    //拿到上次所砍掉的价格
    public static function getBeforeMoney ( $bargain_id = 0, $limit = 1) {
        $beforemoney_sum = 0;
        $sql = "SELECT SUM(`bargain_money`) AS beforemoney_sum FROM 
                (SELECT `bargain_money` FROM `hp_activity_bargain_list` 
                WHERE `bargain_id` = $bargain_id
                ORDER BY `id` DESC
                LIMIT $limit) sum";
         
        $res = Db::query($sql);
        if (is_not_empty_array($res)) {
            $beforemoney_sum = $res[0]['beforemoney_sum'];
        }
        return $beforemoney_sum;
    }
    
     /**
     * 砍价相关数据操作
     *$bargain_id    [activity_bargainirg] 表主键id
     *$sponsor_id    砍价发起者id
     *$assistor_id   帮助砍价者id
     *$min           最小值
     *$max           最大值
     *$join_count    设置要参与砍价的人数
     *return bool
     */
    public static function givePartBargain($bargain_id = 0, $sponsor_id = 0, $assistor_id = 0, $min = 0, $max = 0,$join_count = 0) {
        $state = false;
        if (is_positive_integer($assistor_id) && $bargain_id > 0 && is_positive_integer($sponsor_id)) {
            $bargainirg_info = Db::name('activity_bargainirg')->find($bargain_id);
 
            if ( !$bargainirg_info ) {
                return $state;
            }
 
            $fp = fopen('./bargain_lock.txt','r');
            $try = 5; 
            do {
                $lock = flock($fp,LOCK_EX);
                if(!$lock)
                    usleep(5000); 
            } while (!$lock && --$try >= 0) ;
            if ($lock) {
                Db::startTrans();
                try {
                    $bargain_money = self::returnRandMoney($bargain_id, $min, $max, $join_count);
                    /*-------------*/
                    $id  = 0;
                    $sql = "UPDATE `hp_activity_bargainirg` 
                            SET `deal_money` = `deal_money` - $bargain_money,`bargain_count` = `bargain_count`+ 1 
                            WHERE `id` = $bargain_id AND `user_id` = $sponsor_id AND `deal_money` > $bargain_money
                            AND `bargain_count` < $join_count";
                    $row = self::execute($sql);
                    if ( $row > 0) {
                        $insert_data = [];
                        $insert_data['bargain_id']      = $bargain_id;
                        $insert_data['assistor_id']     = $assistor_id;
                        $insert_data['bargain_money']   = $bargain_money;
                        $insert_data['create_time']     = time();
                        $id = Db::name('activity_bargain_list')->insert($insert_data);
                    }
                    /*-------------*/
                    if ($id > 0) 
                        $state = true; 
                    Db::commit();
                }catch(\Exception $e){
                    $state = false;
                    Db::rollback();
                }
　　　　　　　　flock($lock,LOCK_UN);
　　　　　　　　fclose($lock);
 
            } 
        }
        if ($state !== false ) {
            return $bargain_money;
        }
        return $state;
    }
 
    //返回要砍的价格
    public static function returnRandMoney ($bargain_id = 0, $min = 0 ,$max = 0, $join_count = 0 ){
        $randMoney       = self::randomFloat( $min, $max);                  //返回随机价格  
        $prev_Progress   = self::getBargainirgProgress($bargain_id);            
        $prev_bargain_count = $prev_Progress['bargain_count'];              //返回已经被砍价的次数  
        $remainder = $prev_bargain_count % 3; 
 
        $bout_count = floor($join_count / 3) * 3;  //最后一轮结束的刀数       39
        $last_num = $join_count - $bout_count;
        $avg = ($min + $max) / 2;
        $before_sum  = self::getBeforeMoney($bargain_id, $remainder);
 
        if ($prev_bargain_count >= $bout_count) {
            if ($last_num == 1){
                return $avg;
            } elseif ($last_num == 2) {
                $end = $join_count - $prev_Progress['bargain_count'] ;
                if ($end == 2) {
                    return $randMoney;
                } elseif($end == 1) {
                    return $avg * 2 - $before_sum;
                }
            }  
        }
        // $remainder_num   = $join_count % 3;         //总回合数的余数
        if ($remainder > 0) {
            if ( $remainder == 1) { 
                $point      = $max * 0.8;    //最大额度的80%
                $bout_sum   = 3 * $avg;
                if ($before_sum >= $point) {
                    $randMoney = self::randomFloat($min, ($bout_sum - $before_sum) / 2);
                } else {
                    $randMoney = self::randomFloat(($bout_sum - $before_sum) / 2 , $point);
                }
            }
            if ($remainder == 2) {
                $round_sum_money = 3 * $avg;            
                $randMoney       = $round_sum_money - $before_sum;
            }
        } 
        return $randMoney;
                
    }
    //拿随机价格
    public static function randomFloat($min = 0, $max = 1) {
         return round($min + mt_rand() / mt_getrandmax() * ($max - $min),2);
    }
 
 
 
   //拿砍价活动下所有商品
    public static function getActivityBargainProducts ( $limit = 0, $offset = 0) {
        $data = [];
        $sql = "SELECT a.`id`,a.`product_id`,a.`activity_money`,a.`bargain_section`,a.`join_count`,a.`product_desc`,a.`product_name`,
                a.`attr1_id`,a.`attr2_id`,
                b.`give_score`,b.`category_img`,b.`add_money`,b.`category_sum`
                FROM `hp_activity_bargain` AS a
                LEFT JOIN `hp_category_attr` AS b
                ON a.`attr1_id` = b.`attr1_son_id` AND a.`attr2_id` = b.`attr2_son_id` AND a.`product_id` = b.`category_id`
                WHERE 1 = 1
                ORDER BY a.`id` DESC
                LIMIT $limit OFFSET $offset";
        $data = self::query($sql);        
        return $data;
    }

}